<template>
  <div>
    <div style="display: flex;width: 100%;justify-content: space-around;">
      <div style="width: 250px;height: 250px;" id="template1"></div>
      <div style="width: 250px;height: 250px;" id="template2"></div>
      <div style="width: 250px;height: 250px;" id="template3"></div>
    </div>
    <div style="margin-top: 20px;">
      <h2>设定温度值峰值：{{ tempTop }}</h2>
      <input type="text" v-model="tempTop" placeholder="请输入您的温度峰值">
      <button @click="sendMessage()" v-show="fs">关闭风扇</button>
      <button @click="sendMessage()" v-show="!fs">开启风扇</button>
      <button v-show="!auto" @click="auto = true">自动模式</button>
      <button v-show="auto" @click="auto = false">取消自动</button>
      <img src="./assets/fs.png" alt="" style="width: 50px;height: 50px;margin-left: 100px;" :class="fs ? 'rotating-element' : '' ">
    </div>
    <div style="width: 800px;height: 300px;margin-top: 20px;" id="template4"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import io from 'socket.io-client';
import * as echarts from 'echarts';

const temp = ref(20);
const hum = ref(60);
const gz = ref(2);
const rt = ref(3.44);
const tempTop = ref(25);
const time = ref([]);
const datas = ref([]);
const fs = ref(false);
// 自动模式
const auto = ref(false);

const chartInstance1 = ref(null);
const chartInstance2 = ref(null);
const chartInstance3 = ref(null);
const chartInstance4 = ref(null);

const option1 = {
  tooltip: {
    formatter: '{a} <br/>{b} : {c}%'
  },
  series: [
    {
      name: 'Pressure',
      type: 'gauge',
      progress: {
        show: true
      },
      detail: {
        valueAnimation: true,
        formatter: '{value}',
        fontSize: 20
      },
      pointer: {
        show: true,
        length: '60%'
      },
      data: [
        {
          value: temp.value,
          name: '温度'
        }
      ]
    }
  ]
};

const option2 = {
  tooltip: {
    formatter: '{a} <br/>{b} : {c}%'
  },
  series: [
    {
      name: 'Pressure',
      type: 'gauge',
      progress: {
        show: true
      },
      detail: {
        valueAnimation: false,
        formatter: '{value}',
        fontSize: 20
      },
      data: [
        {
          value: hum.value,
          name: '湿度'
        }
      ],
      pointer: {
        show: true,
        length: '60%'
      },
      title: {}
    }
  ]
};

const option3 = {
  series: [
    {
      type: 'gauge',
      min: 0,
      max: 10,
      axisTick: {
        interval: 10
      },
      axisLine: {
        lineStyle: {
          width: 15,
          color: [
            [0.3, '#67e0e3'],
            [0.7, '#37a2da'],
            [1, '#fd666d']
          ]
        }
      },
      pointer: {
        itemStyle: {
          color: 'auto'
        }
      },
      axisTick: {
        distance: -0,
        length: 8,
        lineStyle: {
          color: '#fff',
          width: 2
        }
      },
      splitLine: {
        distance: -15,
        length: 15,
        lineStyle: {
          color: '#fff',
          width: 4
        }
      },
      axisLabel: {
        color: 'inherit',
        distance: 25,
        fontSize: 15
      },
      detail: {
        valueAnimation: true,
        formatter: '{value} km/h',
        color: 'inherit',
        fontSize: 15
      },
      data: [
        {
          value: 4,
          name: '风速度'
        }
      ]
    }
  ]
};

// 光照强度的数据
const option4 = {
        title: {
            text: '光照强度变化曲线',
            left: 'center'
        },
        tooltip: {},
        xAxis: {
            type: 'category',
            data: time.value
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            name: '数据',
            type: 'line',
            data: datas.value,
            smooth: true,  // 平滑曲线
            itemStyle: {
                normal: {
                    color: '#ff8c00' // 线条颜色
                }
            }
        }]
    };


const getEchart = (domId, option) => {
  const dom = document.getElementById(domId);
  if (dom) {
    const myChart = echarts.init(dom);
    myChart.setOption(option);
    return myChart;
  }
  return null;
};

let socket = null;

const sendMessage=()=> {
  if (auto.value){
    alert("自动模式下无法操作风扇");
    return;
  }
  // 发送消息到服务器
  if (fs.value) {
  socket.emit('fs_status', '0');
  }else{
  socket.emit('fs_status', '1');
  }
}



onMounted(() => {
  console.log("页面挂载完成");
  chartInstance1.value = getEchart("template1", option1);
  chartInstance2.value = getEchart("template2", option2);
  chartInstance3.value = getEchart("template3", option3);
  chartInstance4.value = getEchart("template4", option4);

  // 连接到服务器
  socket = io('http://localhost:8888');
  socket.on('data', function(res) {
    // console.log(chartInstance1.value);
    var data = JSON.parse(res);
    temp.value = +data.temp; // 确保数据类型一致
    hum.value = +data.hum;
    gz.value = +data.gz;
    rt.value = +data.rt;
    if (auto.value) {
      fs.value = temp.value > tempTop.value
    }else{
      fs.value = +data.fs_status>0?true:false;
    }
    

    // 更新 ECharts 实例
    if (chartInstance1.value) chartInstance1.value.setOption({ series: [{ data: [{ value: temp.value,name: '温度'  }] }] });
    if (chartInstance2.value) chartInstance2.value.setOption({ series: [{ data: [{ value: hum.value,name: '湿度' }] }] });
    if (chartInstance3.value) chartInstance3.value.setOption({ series: [{ data: [{ value: gz.value,name: '风速度' }] }] });
    // if (chartInstance4.value) chartInstance4.value.setOption({ series: [{ data: [{ value: rt.value,name: '光照强度' }] }] });

    let now = new Date();
    let newTime = now.toTimeString().split(' ')[0]; // 获取当前时间作为 x 轴数据
    
        // 添加新数据
    time.value.push(newTime);
    datas.value.push(+data.gz);
    // 限制 x 轴和 y 轴的数据长度
    if (time.value.length > 10) {
            time.value.shift(); // 移除最旧的时间
            datas.value.shift(); // 移除对应的数据
        }
    if (chartInstance4.value) {
      chartInstance4.value.setOption({
        xAxis: {
            data: time.value
        },
        series: [{
            data: datas.value
        }]
      });
    }

      });
});

onUnmounted(() => {
  // 组件销毁时，销毁 ECharts 实例
  if (chartInstance1.value) chartInstance1.value.dispose();
  if (chartInstance2.value) chartInstance2.value.dispose();
  if (chartInstance3.value) chartInstance3.value.dispose();
  if (chartInstance4.value) chartInstance4.value.dispose();
  if (socket) socket.disconnect();
});
</script>

<style scoped>
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(720deg);
  }
}

.rotating-element {
  animation: spin 1s linear infinite; /* 2秒完成一次旋转，线性速度，无限循环 */
}
</style>